package com.goldze.mvvmhabit.ui.tab_bar.fragment.chat;

import android.app.Application;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.support.annotation.NonNull;
import android.view.View;

import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.entity.response.GetChatUsersResponseEntity;
import com.goldze.mvvmhabit.ui.chat.ChatContentListActivity;
import com.goldze.mvvmhabit.utils.RelativeDateFormat;
import com.goldze.mvvmhabit.utils.RetrofitClient;
import com.goldze.mvvmhabit.utils.UserManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class ChatViewModel extends BaseViewModel<DemoRepository> {

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public ChatViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //给RecyclerView添加ItemBinding
    public ItemBinding<ChatItemViewModel> itemBinding = ItemBinding.of(com.goldze.mvvmhabit.BR.viewModel, R.layout.item_chatlist);

    //给RecyclerView添加ObservableList
    public ObservableList<ChatItemViewModel> observableList = new ObservableArrayList<>();

    public SingleLiveEvent<String> numMsg = new SingleLiveEvent<>();

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getChatUsers();
        }
    });

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
    }

    public void getChatUsers() {
        if (isDelectState) {
            uc.finishRefreshing.call();
            return;
        }
        model.getChatUsers()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<List<GetChatUsersResponseEntity>>>() {
                    @Override
                    public void accept(BaseResponse<List<GetChatUsersResponseEntity>> response) throws Exception {
                        if (response.isSuccess()) {
                            observableList.clear();
                            for (GetChatUsersResponseEntity entity : response.getResponse()) {
                                if (entity.isIsDelete()) {
                                    return;
                                }
                                if (entity.getFriendAvatar() == null) {
                                    entity.setFriendAvatar("");
                                } else {
                                    entity.setFriendAvatar(RetrofitClient.baseUrl + entity.getFriendAvatar());
                                }
                                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:m:s");
                                try {
                                    Date date = format.parse(entity.getStartTime());
                                    entity.setTimeDistance(RelativeDateFormat.format(date));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                ChatItemViewModel itemViewModel = new ChatItemViewModel(ChatViewModel.this, entity);
                                //双向绑定动态添加Item
                                observableList.add(itemViewModel);
                            }
                        } else {
                            ToastUtils.showShort("获取聊天列表失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        //请求刷新完成收回
                        uc.finishRefreshing.call();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                        //请求刷新完成收回
                        uc.finishRefreshing.call();
                    }
                });
    }

    public void jumpChatContentList() {
        setHasRead();
        startActivity(ChatContentListActivity.class);
    }

    /**
     * 是否点击了删除按钮   true: 处于删除状态下
     */
    public boolean isDelectState = false;
    public ObservableField<String> delectBtnText = new ObservableField<>("删除");

    /**
     * 刷新界面
     *
     * @param index
     * @param mo
     */
    public void notifyBtnState(int index, GetChatUsersResponseEntity mo) {
        observableList.remove(index);
        mo.setChecked(!mo.isChecked());
        ChatItemViewModel itemViewModel = new ChatItemViewModel(ChatViewModel.this, mo);
        observableList.add(index, itemViewModel);
    }

    public void resetItemState() {
        if (isDelectState) {
            delectBtn(null);
        }
    }

    /**
     * 点击按钮
     *
     * @param view
     */
    public void delectBtn(View view) {
        isDelectState = !isDelectState;
        delectBtnText.set(isDelectState ? "完成" : "删除");

        for (int i = 0; i < observableList.size(); i++) {
            GetChatUsersResponseEntity mo = new GetChatUsersResponseEntity();
            mo = observableList.get(i).entity.get();
            mo.setIsShow(isDelectState ? View.VISIBLE : View.GONE);
            if (isDelectState) mo.setChecked(false);
            observableList.remove(i);
            ChatItemViewModel itemViewModel = new ChatItemViewModel(ChatViewModel.this, mo);
            observableList.add(i, itemViewModel);
        }

        if (!isDelectState) {
            for (int i = observableList.size() - 1; i >= 0; i--) {
                if (observableList.get(i).entity.get().isChecked()) {
                    delectItem(observableList.get(i).entity.get().getFriendId(), i);
                }
            }
        }
    }

    private void delectItem(final String friend, final int index) {

        model.DelectUsers(friend)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        if (response.isSuccess() && response.getCode() == 200) {
                            observableList.remove(index);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    public void setHasRead() {
        if (UserManager.getAppManager().getGetChatUsers() == null) {
            return;
        }
        numMsg.call();
        model.setHasRead(UserManager.getAppManager().getGetChatUsers().getFriendId())
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<Boolean>>() {
                    @Override
                    public void accept(BaseResponse<Boolean> response) throws Exception {
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    public int getItemPosition(ChatItemViewModel mChatItemViewModel) {
        return observableList.indexOf(mChatItemViewModel);
    }
}
